package com.lianxi.shiro.realm;

import com.lianxi.pojo.User;
import com.lianxi.shiro.SecurityService.SecurityService;
import com.lianxi.shiro.SecurityService.SecurityServiceImpl;
import com.lianxi.shiro.utils.DigestsUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;
import java.util.Map;

public class DefinitionRealm extends AuthorizingRealm {


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //拿到用户认证凭证信息
        User user = (User) principals.getPrimaryPrincipal();
        String loginName=user.getName();
        //从数据库中查询对应的角色和资源
        SecurityService securityService = new SecurityServiceImpl();
        List<String> roles = securityService.findRoleByloginName(loginName);
        List<String> permissions = securityService.findPermissionByloginName(loginName);
        //构建资源校验
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //从AuthenticationToken中获得登录名称
        String loginName = (String) token.getPrincipal();
        //模拟从数据库当中获取用户名密码 ---
        SecurityService securityService = new SecurityServiceImpl();
        Map<String, String> map = securityService.findPasswordByLoginName(loginName);
        String password = map.get("password");
        if (map.isEmpty()) {
            throw new UnknownAccountException("用户不存在！");
        }
        //传递账号和密码
        //传递账号和密码:参数1：缓存对象，参数2：明数据库文密码(真正的密码)，参数三：字节salt,参数4：当前DefinitionRealm名称
        User user = new User();
        user.setAge(11);
        user.setName(loginName);
        return new SimpleAuthenticationInfo(user, password, ByteSource.Util.bytes(map.get("salt")), getName());
    }


    /**
     * @Description 构造函数
     */
    public DefinitionRealm() {
        //指定密码匹配方式为sha1
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(DigestsUtil.SHA1);
        //指定密码迭代次数
        matcher.setHashIterations(DigestsUtil.ITERATIONS);
        //使用父亲方法使匹配方式生效
        setCredentialsMatcher(matcher);
    }
}
